﻿using System.Collections.Generic;
using System.IO;
using HtmlAgilityPack;
using System.Linq;

namespace RatingAuthor
{
  internal class RatingAuthorParser : IParser
  {
    private const string RecordsXPath = "/html[1]/body[1]/center[2]/table[1]";
    private const string PagesCountXPath = "/html[1]/body[1]/center[2]/table[1]/tr[1]/td[1]/center[1]/b[1]";

    public string IndexedTamplateUrl
    {
      get { return "http://zhurnal.lib.ru/rating/author/index{0}.shtml"; }
    }

    public string Name
    {
      get { return "RatingAuthor"; }
    }

    public PageData Parse(Page page)
    {
      var root = page.Load().DocumentNode;
      return new PageData
      {
        PageIndex = page.Index,
        Records = ParseRecords(root.SelectSingleNode(RecordsXPath), page.Index * 200 + 2).ToList(),
        OveralPagesCount = PagesCountParser.Parse(root.SelectSingleNode(PagesCountXPath).InnerText),
      };
    }

    private static IEnumerable<BookRecord> ParseRecords(HtmlNode table, int row)
    {
      var counter = 0;
      var book = new BookRecord();
      foreach (var n in table.Elements("td"))
      {
        switch (counter % 5)
        {
          case 0:
            int num;
            if (!int.TryParse(n.InnerText, out num) || num != row++)
              yield break;
            book = new BookRecord();
            break;
          case 1:
            book.SetAuthorUrl(Path.GetDirectoryName(
              n.ChildNodes[0].Attributes["href"].Value));
            book.SetAuthorName(n.ChildNodes[0].InnerText);
            break;
          case 2:
            book.SetUrl(n.ChildNodes[0].Attributes["href"].Value);
            book.SetTitle(n.ChildNodes[0].InnerText);
            book.SetSize(n.ChildNodes[2].ChildNodes[0].InnerText);
            book.SetGanres(n.ChildNodes[2].ChildNodes[1].InnerText);
            break;
          case 3:
            book.SetMark(n.InnerHtml);
            break;
          case 4:
            book.SetMarksCount(n.InnerHtml);
            yield return book;
            break;
        }
        counter++;
      }
    }
  }
}